<template>
  <a-modal
    :destroy-on-close="true"
    :mask-closable="false"
    title="角色管理"
    :width="1200"
    :height="400"
    :open="visible"
    :onCancel="onCancel"
  >
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="1" tab="功能权限" class="menu">
        <a-table
          :rowKey="(record) => record.id"
          :columns="authColumns"
          :data-source="authData"
          :row-selection="rowSelectionAuth"
        />
      </a-tab-pane>
      <a-tab-pane key="2" tab="组件权限">
        <a-table
          :rowKey="(record) => record.id"
          :columns="componentColumns"
          :data-source="componentData"
          :row-selection="rowSelectionCom"
          :pagination="pagination"
        />
      </a-tab-pane>
    </a-tabs>
    <template #footer>
      <a-button key="back" @click="() => onCancel()">取消</a-button>
      <a-button
        key="submit"
        :loading="onSubmitLoading"
        type="primary"
        @click="() => onFinish()"
        >确定</a-button
      >
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
import { computed, defineProps, ref, watch } from "vue";
import { detailData } from "../service";
import { queryComList } from "@/views/compManager/service";
import { useStore } from "vuex";
import { StateType as ListStateType } from "../store";
const props = defineProps<{
  visible: boolean;
  onSubmitLoading: boolean;
  onCancel: Function;
  roleId: number | string | undefined;
  onSubmit: Function;
}>();
const activeKey = ref("1");
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      getRoleDetail();
      getComponents(1);
    }
  },
  { deep: true, immediate: true }
);
const roleDetail = ref({});
const getRoleDetail = async () => {
  const res = await detailData({ id: props.roleId });
  if (res.success) {
    roleDetail.value = res.data;
    authData.value = recursiveDelete(res.data.permissionList);
  }
};

const recursiveDelete = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children.length <= 0) {
      delete arr[i].children;
    } else {
      recursiveDelete(arr[i].children);
    }
  }
  return arr;
};
const store = useStore<{ ListSearchTable: ListStateType }>();
// 列表分页
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0, // 假设总共有100条数据
  showTotal: (total) => `共 ${total} 条数据`,
  onChange: (page, pageSize) => {
    // 分页改变时的回调函数
    pagination.value.current = page;
    pagination.value.pageSize = pageSize;
    getComponents(page);
  },
  showSizeChanger: true,
  showQuickJumper: true,
});
const getComponents = async (current: number) => {
  const params = {
    pageNum: pagination.value.current,
    pageSize: pagination.value.pageSize,
    roleId: props.roleId,
    enableStatus: "1",
  };
  const res = await queryComList(params);
  if (res.success) {
    componentData.value = res.data.records;
    pagination.value.total = res.data.total;
    // componentData.value.forEach(ele => {
    //     if (ele.checked) {
    //         rowSelectionCom.value.selectedRowKeys.push(ele.id)
    //         selectedComRowKeys.value.push(ele.id)
    //     }
    // })
  }
};
const authColumns = [
  {
    title: "权限资源名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "类型",
    dataIndex: "type",
    key: "type",
    customRender: ({ text }: { text: any }) => {
      if (text === "catalog") {
        return "目录";
      } else if (text === "menu") {
        return "菜单";
      } else if (text === "button") {
        return "功能按钮";
      } else if (text === "page") {
        return "页面";
      }
    },
  },
  {
    title: "地址",
    dataIndex: "path",
    key: "path",
  },
  {
    title: "权限标识",
    dataIndex: "code",
    key: "code",
  },
];
const componentColumns = [
  {
    title: "组件名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "组件地址",
    dataIndex: "url",
    key: "url",
  },
  {
    title: "组件类别",
    dataIndex: "type",
    key: "type",
  },
  {
    title: "默认地址",
    dataIndex: "defaultPath",
    key: "defaultPath",
  },
];
const authData = ref([]);
const componentData = ref([]);

// const componentIdList = ref([])
// const permissionIdList = ref([])

const selectedPermissionIds = computed(
  () => roleDetail.value.permissionIdList || []
);

const selectedComponentIds = computed(
  () => roleDetail.value.componentIdList || []
);

const rowSelectionAuth = ref({
  onChange: (selectedRowKeys: (string | number)[], selectedRows: []) => {
    if (selectedRows.length <= 0) {
      roleDetail.value.permissionIdList = [];
    } else {
      let ids = selectedRows.map((e) => e.id);
      roleDetail.value.permissionIdList = Object.assign([], ids);
    }
  },
  selectedRowKeys: selectedPermissionIds,
  // onSelect: (record: {}, selected: boolean, selectedRows:[]) => {
  //     console.log(record, selected, selectedRows);
  // },
  // onSelectAll: (selected: boolean, selectedRows:[], changeRows: []) => {
  //     console.log(selected, selectedRows, changeRows);
  // },
});
const rowSelectionCom = ref({
  onChange: (selectedRowKeys: (string | number)[], selectedRows: []) => {
    if (selectedRows.length <= 0) {
      roleDetail.value.componentIdList = [];
    } else {
      let ids = selectedRows.map((e) => e.id);
      roleDetail.value.componentIdList = Object.assign([], ids);
    }
  },
  selectedRowKeys: selectedComponentIds,
});
const onFinish = () => {
  const req = {
    appId: roleDetail.value.appId,
    componentIdList: roleDetail.value.componentIdList,
    id: roleDetail.value.id,
    permissionIdList: roleDetail.value.permissionIdList,
    updateType: "2",
    roleCode: roleDetail.value.roleCode,
    roleName: roleDetail.value.roleName,
    enableStatus: roleDetail.value.enableStatus,
  };
  props.onSubmit(req);
};
</script>
<style scoped lang="less">
.menu {
  :deep(.ant-table-pagination) {
    display: none;
  }
}
</style>
